﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace LaserTag.Common.Behaviors
{
        public class WindowDragMove : Behavior<Window>
        {
            private Point? m_lastLocation;

            protected override void OnAttached()
            {
                base.OnAttached();

                AssociatedObject.MouseMove += Window_PreviewMouseMove;
                AssociatedObject.MouseUp += Window_PreviewMouseUp;
                AssociatedObject.LocationChanged += Window_LocationChanged;
                AssociatedObject.MouseDown += Window_PreviewMouseDown;
            }

            protected override void OnDetaching()
            {
                AssociatedObject.MouseMove -= Window_PreviewMouseMove;
                AssociatedObject.MouseUp -= Window_PreviewMouseUp;
                AssociatedObject.LocationChanged -= Window_LocationChanged;
                AssociatedObject.MouseDown -= Window_PreviewMouseDown;
                base.OnDetaching();
            }

            private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
            {
                AssociatedObject.CaptureMouse();
                m_lastLocation = AssociatedObject.PointToScreen(Mouse.GetPosition(AssociatedObject));
            }

            private void Window_LocationChanged(object sender, EventArgs e)
            {
                m_lastLocation = AssociatedObject.PointToScreen(Mouse.GetPosition(AssociatedObject));
            }

            private void Window_PreviewMouseUp(object sender, MouseButtonEventArgs e)
            {
                if (AssociatedObject.IsMouseCaptured)
                    AssociatedObject.ReleaseMouseCapture();
            }

            private void Window_PreviewMouseMove(object sender, MouseEventArgs e)
            {
                if (Mouse.LeftButton != MouseButtonState.Pressed)
                    return;

                AssociatedObject.CaptureMouse();

                Point currentLocation = AssociatedObject.PointToScreen(Mouse.GetPosition(AssociatedObject));

                if (m_lastLocation == null)
                    m_lastLocation = currentLocation;

                if (m_lastLocation == currentLocation)
                    return;

                var diff = currentLocation - m_lastLocation.Value;

                AssociatedObject.Top += diff.Y;
                AssociatedObject.Left += diff.X;

                m_lastLocation = currentLocation;
            }
        }
    }
